<template>
  <div class="change-password">
    <h1>修改密码</h1>
    <el-form :model="passwordForm" :rules="rules" label-width="100px" style="max-width: 600px" ref="formRef">
      <el-form-item label="用户名" prop="username">
        <el-input v-model="passwordForm.username" disabled />
      </el-form-item>
      <el-form-item label="原密码" prop="oldPassword">
        <el-input v-model="passwordForm.oldPassword" type="password" show-password />
      </el-form-item>
      <el-form-item label="新密码" prop="newPassword">
        <el-input v-model="passwordForm.newPassword" type="password" show-password />
      </el-form-item>
      <el-form-item label="确认密码" prop="confirmPassword">
        <el-input v-model="passwordForm.confirmPassword" type="password" show-password />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm">保存修改</el-button>
        <el-button @click="resetForm">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import {changePasswordService, getUserInfoService} from '@/api/user.js'
import useUserInfoStore from '@/stores/userInfo.js'

const passwordForm = ref({
  username: '',
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

const userInfoStore = useUserInfoStore()

onMounted(() => {
  passwordForm.value.username = userInfoStore.info.username || ''
})

const formRef = ref(null)

// 确认密码校验
const validateConfirmPassword = (rule, value, callback) => {
  if (value !== passwordForm.value.newPassword) {
    callback(new Error('两次输入密码不一致!'))
  } else {
    callback()
  }
}

const rules = {
  oldPassword: [
    { required: true, message: '请输入原密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    { validator: validateConfirmPassword, trigger: 'blur' }
  ]
}

// 保存修改
const submitForm = () => {
  formRef.value.validate(async valid => {
    if (valid) {
      let result = await changePasswordService(passwordForm.value);
      ElMessage.success(result.msg ? result.msg : '修改成功');
    }
  })
}

const loading = ref(false)
const getUserInfo = async () => {
  loading.value = true;
  let result = await getUserInfoService();
  passwordForm.value.username = result.data.username;
}

getUserInfo()

const resetForm = () => {
  passwordForm.value = {
    username: 'admin',
    oldPassword: '',
    newPassword: '',
    confirmPassword: ''
  }
}
</script>

<style scoped>
.change-password {
  padding: 20px;
}
</style>